//
//  RecordView.m
//  录音
//
//  Created by YangLiang on 16/5/27.
//  Copyright © 2016年 YangLiang. All rights reserved.
//

#import "RecordView.h"

@interface RecordView () {
    //秒数
    NSInteger second;
    NSInteger addSecond;
    
    AVAudioRecorder *recorder;//录音器
    AVAudioSession *session;
    NSDictionary *recorderSettingsDict;
    NSString *playName;
}

//倒计时
@property (nonatomic, strong) UILabel *timeLabel;

//录音按键
@property (nonatomic, strong) UIButton *recordButton;

//定时器
@property (nonatomic, strong) NSTimer *timer;



@end

@implementation RecordView

// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}

#pragma mark -
- (instancetype)initWithFrame:(CGRect)frame {
    if (self == [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorFromHexCode:@"f4f4f6"];
        second = 60;
        addSecond = 0;
        [self addSubview:self.timeLabel];
        [self addSubview:self.recordButton];

    }
    return self;
}

#pragma mark - 私有方法
/**
 *  设置音频会话
 */
-(void)setAudioSession{
    AVAudioSession *audioSession=[AVAudioSession sharedInstance];
    //设置为播放和录音状态，以便可以在录制完之后播放录音
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    [audioSession setActive:YES error:nil];
}

#pragma mark - 录音按键响应事件
//开始录音
- (void)recordButtonClickStart:(UIButton *)button {
    [self startRecordSource];
}
//结束录音
- (void)recordButtonClickStop:(UIButton *)button {
    [self stopRecordSource];
    _timeLabel.text = nil;
    
}

#pragma mark - 定时器响应事件
- (void)timerClick:(NSTimer *)timer {
    //根据时间判断是否继续录音
    if (second >= 1) {
        _timeLabel.text = [NSString stringWithFormat:@"剩余%ld秒",(long)--second];
        addSecond = addSecond + 1;
    }else {
        [self deallocTimer];
    }
}

- (void)deallocTimer {
    //
    second = 60;
    //
    [recorder stop];
    recorder = nil;
    //销毁定时器
    [_timer invalidate];
    _timer = nil;
    
    //回调 结束录音 将音频路径传回VC
    if (_recordBlockVoiceStr) {
        [self setAudioSession];
        _recordBlockVoiceStr(playName,[NSString stringWithFormat:@"%ld",addSecond]);
    }
}

#pragma mark - ===
#pragma mark - 开始录音
- (void)startRecordSource {
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
        session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        
        if (session == nil) {
            NSLog(@"Error creating session:%@",[sessionError description]);
        }else {
            [session setActive:YES error:nil];
        }
    }
    
//    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];

    playName = [NSString stringWithFormat:@"%@/play.caf",docDir];
    //录音设置
    recorderSettingsDict =[[NSDictionary alloc] initWithObjectsAndKeys:
                           [NSNumber numberWithInt:kAudioFormatLinearPCM],AVFormatIDKey,
                           [NSNumber numberWithFloat:44100],AVSampleRateKey,
                           [NSNumber numberWithInt:1],AVNumberOfChannelsKey,
                           [NSNumber numberWithInt:16],AVLinearPCMBitDepthKey,
                           [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                           [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                           [NSNumber numberWithInt:AVAudioQualityHigh],
                           AVEncoderAudioQualityKey,
                           nil];
    //按下录音
    if ([self canRecord]) {
        NSError *error = nil;
        //必须真机上测试,模拟器上可能会崩溃
        recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:playName] settings:recorderSettingsDict error:&error];
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
        }
        
        if (recorder) {
            recorder.meteringEnabled = YES;
            [recorder prepareToRecord];
            [recorder record];
            //启动定时器
            [self.timer fire];
        }
    }
}

#pragma mark - 结束录音
- (void)stopRecordSource {
    [self deallocTimer];
    
    session = [AVAudioSession sharedInstance];
    NSError *sessionError;
    [session setCategory:AVAudioSessionCategoryPlayback error:&sessionError];
    if(session == nil){
        NSLog(@"Error creating session: %@", [sessionError description]);
    }else{
        [session setActive:YES error:nil];
    }
    addSecond = 0;
}


#pragma mark - 判断是否允许使用麦克风7.0新增的方法requestRecordPermission
-(BOOL)canRecord {
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending) {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                if (granted) {
                    bCanRecord = YES;
                }else {
                    bCanRecord = NO;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[[UIAlertView alloc] initWithTitle:nil
                                                    message:@"app需要访问您的麦克风。\n请启用麦克风-设置/隐私/麦克风"
                                                   delegate:nil
                                          cancelButtonTitle:@"关闭"
                                          otherButtonTitles:nil] show];
                    });
                }
            }];
        }
    }
    return bCanRecord;
}

#pragma mark -
- (UILabel *)timeLabel {
    if (!_timeLabel) {
        _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 20)];
        _timeLabel.textAlignment = NSTextAlignmentCenter;
        _timeLabel.textColor = [[UIColor blackColor] colorWithAlphaComponent:0.75];
        _timeLabel.font = [UIFont systemFontOfSize:14];
    }
    return _timeLabel;
}

- (UIButton *)recordButton {
    if (!_recordButton) {
        _recordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _recordButton.frame = CGRectMake(self.bounds.size.width/2-35, 30, 70, 70);
        
        //        [_recordButton setBackgroundColor:[UIColor redColor]];
        [_recordButton setImage:[[UIImage imageNamed:@"btn_speak"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
        [_recordButton addTarget:self action:@selector(recordButtonClickStart:) forControlEvents:UIControlEventTouchDown];
        [_recordButton addTarget:self action:@selector(recordButtonClickStop:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    return _recordButton;
}

- (NSTimer *)timer {
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerClick:) userInfo:nil repeats:YES];
    }
    return _timer;
}


@end
